package com.nineclock.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nineclock.common.constant.SMSConstant;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NCException;
import com.nineclock.common.utils.BeanHelper;
import com.nineclock.dto.SysRegisterDTO;
import com.nineclock.dto.SysUserDTO;
import com.nineclock.pojo.SysUser;
import com.nineclock.system.mapper.SysUserMapper;
import com.nineclock.system.service.SmsService;
import com.nineclock.system.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Transactional
@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    /**
     * 根据用户名/手机号查询用户信息
     * @param username
     * @return
     */
    @Override
    public SysUserDTO findUserInfo(String username) {
        if (StringUtils.isEmpty(username)) {
            throw new NCException(ResponseEnum.INVALID_USERNAME_PASSWORD);
        }
        // 封装查询条件
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUsername, username).or().eq(SysUser::getMobile, username);
        // 查询
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper);
        if (ObjectUtil.isNull(sysUser)) {
            throw new NCException(ResponseEnum.USER_NOT_FOUND);
        }
        return BeanHelper.copyProperties(sysUser, SysUserDTO.class);
    }

    @Autowired
    SmsService smsService;
    // 注册用户
    @Override
    public Long register(SysRegisterDTO sysRegisterDTO) {
        // 校验参数
        if (sysRegisterDTO == null || StringUtils.isEmpty(sysRegisterDTO.getMobile()) || StringUtils.isEmpty(sysRegisterDTO.getCheckcode()) || StringUtils.isEmpty(sysRegisterDTO.getPassword())) {
            throw new NCException(ResponseEnum.MESSAGE_PARAMS_LOST);
        }
        // 校验验证码
        Boolean result = smsService.verify(sysRegisterDTO.getCheckcode(), "2", sysRegisterDTO.getMobile());
        if (!result) {
            throw new NCException(ResponseEnum.CODE_IMAGE_ERROR);
        }
        // 注册业务开发
        SysUser sysUser = new SysUser();
        sysUser.setMobile(sysRegisterDTO.getMobile());
        sysUser.setPassword(new BCryptPasswordEncoder().encode(sysRegisterDTO.getPassword()));
        sysUserMapper.insert(sysUser);
        return sysUser.getId();
    }
}
